package com.lzh.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.eduservice.client.VodClient;
import com.lzh.eduservice.entity.EduVideo;
import com.lzh.eduservice.mapper.EduVideoMapper;
import com.lzh.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author lzh
 * @since 2020-12-01
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    //注入vodClient
    @Autowired
    private VodClient vodClient;

    //根据课程id删除小节
    @Override
    public void removeVideoByCourseId(String courseId) {
        //1根据课程id查询所有视频id
        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        //下面两个条件构造器的作用是根据课程id查询视频id，不必把所有的字段都查询出来
        // 相当于查询语句select video_source_id from video where course_id = ?;
        wrapperVideo.eq("course_id", courseId);
        wrapperVideo.select("video_source_id");
        List<EduVideo> eduVideoList = baseMapper.selectList(wrapperVideo);

        //将List<EduVideo>变成List<String>
        //得到所有视频列表的云端原始视频id
        List<String> videoIds = new ArrayList<>();
        for (int i = 0; i < eduVideoList.size(); i++) {
            EduVideo video = eduVideoList.get(i);
            String videoSourceId = video.getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)) {
                videoIds.add(videoSourceId);
            }
            if (videoIds.size() > 0) {
                vodClient.deleteBatch(videoIds);
            }
            //根据课程id删除小节id
            QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
            wrapper.eq("course_id", courseId);
            baseMapper.delete(wrapper);
        }
    }
}
